﻿#define _CRT_SECURE_NO_WARNINGS 1;
#include "Tree.h"

void perOrder(TNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	printf("%c ", root->data);
	perOrder(root->left);
	perOrder(root->right);
}

void inOrder(TNode* root)
{

	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	inOrder(root->left);
	printf("%c ", root->data);
	inOrder(root->right);
}

void postOrder(TNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	postOrder(root->left);
	postOrder(root->right);
	printf("%c ",root->data);
}


//计算二叉树节点个数
int BinaryTreeSize(TNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);;
}

int BinaryTreeLeafSize(TNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

// ⼆叉树第k层结点个数
int BinaryTreeLevelKSize(TNode* root, int k)
{
	if (root == NULL)
		return 0;
	if (k == 1)
			return 1;
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

//⼆叉树的深度/⾼度
int BinaryTreeDepth(TNode* root)
{
	if (root==NULL)
		return 0;
	return 1 + max(BinaryTreeDepth(root->left), BinaryTreeDepth(root->right));
}

// ⼆叉树查找值为x的结点
TNode* BinaryTreeFind(TNode* root, TreeDataType x)
{
	if (root == NULL)
		return NULL;
	if (root->data == x)
	{
		return root;
	}
	TNode* pleft = BinaryTreeFind(root->left,x);
	if (pleft)
		return pleft;

	TNode* pright = BinaryTreeFind(root->right, x);
	if (pright)
		return pright;
	return NULL;
}

// ⼆叉树销毁
void BinaryTreeDestory(TNode** root)
{
	assert(root);
	if (*root == NULL)
		return;
	BinaryTreeDestory(&((*root)->left));
	BinaryTreeDestory(&((*root)->right));
	free(*root);
	*root = NULL;
}

void leveOrder(TNode* root)
{
	if (root == NULL)
		return;
	Queue q;
	QueueInit(&q);
	QueuePush(&q, root);
	while (!QueueEmpty(&q))
	{
		//取队头
		TNode* top = QueueFront(&q);
		QueuePop(&q);
		printf("%c ", top->data);
		//判断队头是否为空,左右孩子入队
		if (top->left != NULL)
			QueuePush(&q, top->left);
		if (top->right != NULL)
			QueuePush(&q, top->right);
	}
	QueueDestroy(&q);
}
